package com.fancy.application.sys.auth.filter;

import cn.hutool.http.HttpRequest;
import com.fancy.application.common.utils.SpringBeanUtil;
import com.fancy.application.sys.auth.config.JwtToken;
import com.fancy.application.sys.permission.service.ISysPermissionMatcher;
import com.fancy.application.sys.permission.service.impl.SysPermissionMatcher;
import lombok.extern.log4j.Log4j2;
import org.apache.shiro.web.filter.PathMatchingFilter;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 权限认证过滤器
 */

@Log4j2
public class FancyPermissionFilter  extends AuthorizationFilter {
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest)request;
        return sysPermissionMatcher.doMatch(httpServletRequest.getRequestURI(),httpServletRequest.getMethod());

    }

    /**
     * 会话超时或登录校验未通过的，统一返回401，由前端页面弹窗提示
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
        WebUtils.toHttp(response).sendError(403);
        return false;
    }

//    protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
//        HttpServletRequest httpServletRequest = (HttpServletRequest)request;
//        return sysPermissionMatcher.doMatch(httpServletRequest.getRequestURI(),httpServletRequest.getMethod());
//    }
//
    @Resource
    private ISysPermissionMatcher sysPermissionMatcher;

}
